package cn.yunhe.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.yunhe.entity.User;

@Controller
public class UserController {
	@RequestMapping("/login")
    public String loginUser(User user,HttpServletRequest request,boolean remb){
		//将用户名和密码 封装到 令牌中
    	UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
    	//获取一个 Subject 实例  , 将当前项目 抽象为一个 subject对象
    	Subject subject = SecurityUtils.getSubject();
    	Cookie[] cks = request.getCookies();
    	for (Cookie ck : cks) {
			System.out.println(ck.getName()+"---------------"+ck.getValue());
		}
    	System.out.println(request.getSession());
    	request.getSession().setAttribute("k1", "tom");
    	System.out.println(subject.getSession());
    	subject.getSession().setAttribute("k2", "jack");
    	try {
    		if(remb){
    		   token.setRememberMe(true);	
    		}else{
    		   token.setRememberMe(false);	
    		}
    		
    		//调用 subject的 登录认证方法
			subject.login(token);
			
			return "success";
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			System.out.println("###########################");
			e.printStackTrace();
			request.setAttribute("msg", "登录失败");
			return "../../index";
		}
    	
    	
    
    }
	@RequestMapping("/edit1User")
	public  String  doEditUserInfo(){
		System.out.println("==========执行修改用户信息1111===========");
		Subject subject = SecurityUtils.getSubject();
		System.out.println(subject.isAuthenticated()+"@@@");
		return  "userEdit";
	}
	
	@RequestMapping("/edit2User")
	public  String  doEditUserInfo2(){
		System.out.println("==========执行修改用户信息2222===========");
		Subject subject = SecurityUtils.getSubject();
		System.out.println(subject.isAuthenticated()+"@@@");
		return  "userEdit";
	}
	
	@RequestMapping("/logout")
	public  String  logoutUser(HttpServletRequest request){
		System.out.println("==========注销===========");
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		System.out.println(request.getSession().getAttribute("k1")+"######");;
		System.out.println(subject.getSession().getAttribute("k2")+"$$$$$$$");;
		Cookie[] cks = request.getCookies();
    	for (Cookie ck : cks) {
			System.out.println(ck.getName()+"---------------"+ck.getValue());
		}
		return  "userEdit";
	}

}
